package edu.spangler.dang.FriendTracker;

import java.nio.ByteBuffer;

import android.location.Location;

/**
 * Converts between bytes and Location objects.
 */

class LocationConverter
{
    /**
     * The number of bytes a Location becomes.
     */
    
    public static final int NumBytes = 8 * 2;
    
    private static final byte[] _data = new byte[NumBytes];
    private static final ByteBuffer _buffer = ByteBuffer.wrap(_data);

    /**
     * Converts a Location to a byte array for passing across a network.
     * @param location The location to convert.
     * @return The location as a byte array.
     */
    
    public static byte[] LocationToBytes(Location location)
    {
        synchronized (_data)
        {
            _buffer.rewind();
            _buffer.putDouble(location.getLatitude());
            _buffer.putDouble(location.getLongitude());
            
            return _data.clone();
        }
    }

    /**
     * Converts a byte array from the network to a Location.
     * @param data The byte data received.
     * @param provider The name of the provider to report in the Location.
     * @return The converted Location.
     */
    
    public static Location BytesToLocation(byte[] data, String provider)
    {
        synchronized (_data)
        {
            _buffer.rewind();
            System.arraycopy(data, 0, _data, 0, NumBytes);
            
            Location location = new Location(provider);
            location.setLatitude(_buffer.getDouble());
            location.setLongitude(_buffer.getDouble());
            
            return location;
        }
    }
}
